package com.handpay.nocardpay.baselibrary.pay.uniopayquick.view;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.NoCardPayApplication;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.cardrecognition.PreviewActivity;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.location.LocationService;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.main.mine.model.bean.MerchInfo;
import com.handpay.nocardpay.baselibrary.main.mine.presenter.MinePresenterImpl;
import com.handpay.nocardpay.baselibrary.main.mine.view.IMerchInfoView;
import com.handpay.nocardpay.baselibrary.pay.uniopayquick.model.bean.UnionQuickPayReqBean;
import com.handpay.nocardpay.baselibrary.pay.uniopayquick.model.bean.UnionQuickPayRespBean;
import com.handpay.nocardpay.baselibrary.pay.uniopayquick.presenter.UnionPayQuickPresenter;
import com.handpay.nocardpay.baselibrary.pay.unipay.model.bean.HistoryBankCardDelBean;
import com.handpay.nocardpay.baselibrary.pay.unipay.model.bean.HistoryBankCardListBean;
import com.handpay.nocardpay.baselibrary.pay.unipay.model.bean.MerchantTypeListBean;
import com.handpay.nocardpay.baselibrary.pay.unipay.presenter.HistoryBankCardListPresenter;
import com.handpay.nocardpay.baselibrary.pay.unipay.presenter.MerchantTypeListPresenter;
import com.handpay.nocardpay.baselibrary.pay.unipay.view.IHistoryCardView;
import com.handpay.nocardpay.baselibrary.pay.unipay.view.IMerchantTypeListView;
import com.handpay.nocardpay.baselibrary.pay.widget.MerchantTypeAdapter;
import com.handpay.nocardpay.baselibrary.pay.widget.NoCardPayListCardNoAdapter;
import com.handpay.nocardpay.baselibrary.permission.PermissionCode;
import com.handpay.nocardpay.baselibrary.permission.PermissionRequest;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ArithUtil;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.widget.BankCardNoEditTextView;
import com.intsig.ccrengine.CCREngine;
import com.intsig.ccrengine.ISCardScanActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.handpay.nocardpay.baselibrary.permission.PermissionCode.REQUEST_CODE_SETTING;

public class UnionPayQuickFragment extends BaseFragment implements View.OnClickListener, IHistoryCardView, IMerchInfoView, IMerchantTypeListView, IUniopayquickView {
    private double mAmount;
    private String tradType;
    private TextView tv_amount, no_card_pay_user_name_tv, no_card_pays_merchant_type_tv;
    private BankCardNoEditTextView no_card_pay_card_no;
    private LinearLayout ll_card, ll_merchant_type, rates_info_ll;
    private ImageButton no_card_pay_card_btn, no_card_pay_camera_btn, merchant_type_btn;
    private Button no_card_pay_next_btn;
    private RelativeLayout rl_arrow;
    private TextView rates_tv;
    private TextView service_charge_tv;
    private TextView arrival_amount_tv;


    private PopupWindow mPopupWindow;

    // 0： 使用sdk内置相机模块 1：使用自定义相机模块 主要是怕更换频繁
    private int useScanType = 1;
    public int isCardRequestCode = 33301;

    //多费率
    private MerchantTypeListPresenter mMerchantTypeListPresenter;
    private List<MerchantTypeListBean.ListBean> mMerchantTypeList;
    private MerchantTypeListBean.ListBean mMerchantTypeBean;
    private String mMerchantType;
    private String merChantClassId;
    //商户信息
    private MinePresenterImpl mMinePresenterImpl;
    private MerchInfo mMerchInfo;

    //历史卡
    private HistoryBankCardListPresenter mHistoryBankCardListPresenter;
    private NoCardPayListCardNoAdapter mNoCardPayListCardNoAdapter;
    private HistoryBankCardListBean.ListBean mHistoryBankCardItem;
    private boolean bIsShowMerchantType = true;


    //银联快捷
    private UnionPayQuickPresenter unionPayQuickPresenter;
    private UnionQuickPayReqBean quickPayReqBean;

    private LocationService locationService;

    private PermissionRequest permissonRequest;
    private PermissionListener permissionListener;
    private String[] permissons = Permission.CAMERA;
    private String[] permissonsLocation = Permission.LOCATION;

    public static UnionPayQuickFragment newInstance(double amount, String tradeType) {
        Bundle args = new Bundle();
        args.putDouble(NoCardPayConstant.AMOUNT, amount);
        args.putString(BaseProtocolKey.TRADETYPE, tradeType);
        UnionPayQuickFragment fragment = new UnionPayQuickFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_uniopay_quick;
    }

    @Override
    public String getFragmentTitle() {
        return _mActivity.getResources().getString(R.string.unionpay);
    }

    @Override
    public void initView(View view) {
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(toolbar, true);

        tv_amount = (TextView) view.findViewById(R.id.tv_amount);
        no_card_pay_user_name_tv = (TextView) view.findViewById(R.id.no_card_pay_user_name_tv);
        no_card_pay_card_no = (BankCardNoEditTextView) view.findViewById(R.id.no_card_pay_card_no);
        no_card_pays_merchant_type_tv = (TextView) view.findViewById(R.id.no_card_pays_merchant_type_tv);

        ll_card = (LinearLayout) view.findViewById(R.id.ll_card);
        ll_merchant_type = (LinearLayout) view.findViewById(R.id.ll_merchant_type);
        rl_arrow = (RelativeLayout) view.findViewById(R.id.rl_arrow);
        rates_info_ll = (LinearLayout) view.findViewById(R.id.rates_info_ll);

        no_card_pay_card_btn = (ImageButton) view.findViewById(R.id.no_card_pay_card_btn);
        no_card_pay_camera_btn = (ImageButton) view.findViewById(R.id.no_card_pay_camera_btn);
        no_card_pay_next_btn = (Button) view.findViewById(R.id.btn_pay);
        merchant_type_btn = (ImageButton) view.findViewById(R.id.merchant_type_btn);

        rates_tv = (TextView) view.findViewById(R.id.rates_tv);
        service_charge_tv = (TextView) view.findViewById(R.id.service_charge_tv);
        arrival_amount_tv = (TextView) view.findViewById(R.id.arrival_amount_tv);
    }

    @Override
    public void initListener() {
        no_card_pay_card_btn.setOnClickListener(this);
        no_card_pay_camera_btn.setOnClickListener(this);
        no_card_pay_next_btn.setOnClickListener(this);
        rl_arrow.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mAmount = getArguments().getDouble(NoCardPayConstant.AMOUNT);

        tradType = getArguments().getString(BaseProtocolKey.TRADETYPE);

        tv_amount.setText(CommonUtils.formatMoneyDouble(ArithUtil.div(mAmount, 100d)) + "元");
        //多费率
        mMerchantTypeListPresenter = new MerchantTypeListPresenter(_mActivity, this);
        //历史卡号
        mHistoryBankCardListPresenter = new HistoryBankCardListPresenter(_mActivity, this);

        //基本信息
        mMinePresenterImpl = new MinePresenterImpl(_mActivity);
        mMinePresenterImpl.setiMerchInfoView(this);

        //银联快捷
        unionPayQuickPresenter = new UnionPayQuickPresenter(_mActivity);
        unionPayQuickPresenter.setiUniopayquickView(this);

        permissonRequest = new PermissionRequest(_mActivity);
        locationService = ((NoCardPayApplication) _mActivity.getApplication()).locationService;
        locationService.registerListener();
        mNoCardPayListCardNoAdapter = new NoCardPayListCardNoAdapter(_mActivity);

        quickPayReqBean = new UnionQuickPayReqBean();


        //permission callback
        permissionListener = new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                switch (requestCode) {
                    case PermissionCode.LOCATION_PERMISSION_CODE:
                        //定位权限获取之后
                        quickPay();
                        break;
                    case PermissionCode.CAMERA_PERMISSION_CODE:
                        //相机权限获取之后
                        goToIsCardSCanActivity();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
                if (AndPermission.hasAlwaysDeniedPermission(_mActivity, deniedPermissions)) {
                    // 第一种：用默认的提示语。
                    AndPermission.defaultSettingDialog(UnionPayQuickFragment.this, PermissionCode.REQUEST_CODE_SETTING).show();
                }
            }
        };
        getMerchinfo();

        getMerchantTypeList();
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.no_card_pay_camera_btn) {
            permissonRequest.requestPermission(PermissionCode.CAMERA_PERMISSION_CODE, permissionListener, permissons);
        } else if (view.getId() == R.id.rl_arrow) {
            showMerchantTypePop(mMerchantTypeList);
        } else if (view.getId() == R.id.no_card_pay_card_btn) {
            getHistoryBankCard();
        } else if (view.getId() == R.id.btn_pay) {
            hideSoftInput();
            permissonRequest.requestPermission(PermissionCode.LOCATION_PERMISSION_CODE, permissionListener, permissonsLocation);
        }
    }


    /**
     * 银行卡识别
     */
    private void goToIsCardSCanActivity() {
        if (useScanType == 0) {
            try {
                Intent intent = new Intent(_mActivity, ISCardScanActivity.class);
                // 指定SDK相机模块ISCardScanActivity四边框角线条,检测到银行卡图片后的颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_MATCH, 0xffff0000);
                // 指定SDK相机模块ISCardScanActivity四边框角线条颜色，正常显示颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_NORMAL, 0xff00ff00);
                // 指定SDK相机模块ISCardScanActivity提示字符串
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_TIPS, _mActivity.getString(R.string.txt_putBankCard_inbox));
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_ORIENTATION, ISCardScanActivity.ORIENTATION_VERTICAL);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_NUMBER_IMG, false);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_TRIMED_IMG, CommonUtils.getAccessDir().getAbsolutePath() + File.separator + "trimedcard.jpg");
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_ORIGINAL_IMG, CommonUtils.getAccessDir().getAbsolutePath() + File.separator + "origianlcard.jpg");
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_APP_KEY, NoCardPayConfig.KEY_CC_CARD);
                HPLog.e(HPLog.LFP_TAG, "KEYS=" + NoCardPayConfig.KEY_CC_CARD);
                startActivityForResult(intent, isCardRequestCode);
            } catch (Exception e) {
                HPLog.e("isCCCard", "出错了");
                e.printStackTrace();
            }
        } else if (useScanType == 1) {
            try {
                Intent intent = new Intent(_mActivity, PreviewActivity.class);
                // 指定SDK相机模块ISCardScanActivity四边框角线条,检测到银行卡图片后的颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_MATCH, 0xffff0000);
                // 指定SDK相机模块ISCardScanActivity四边框角线条颜色，正常显示颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_NORMAL, 0xff00ff00);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_ORIENTATION, ISCardScanActivity.ORIENTATION_VERTICAL);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_NUMBER_IMG, false);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_TRIMED_IMG, CommonUtils.getAccessDir().getAbsolutePath() + File.separator + "trimedcard.jpg");
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_ORIGINAL_IMG, CommonUtils.getAccessDir().getAbsolutePath() + File.separator + "origianlcard.jpg");
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_APP_KEY, NoCardPayConfig.KEY_CC_CARD);
                startActivityForResult(intent, isCardRequestCode);
            } catch (Exception e) {
                HPLog.e("isCCCard", "出错了");
                e.printStackTrace();
            }
        }
    }

    /**
     * show merchantype
     *
     * @param data
     */

    private void showMerchantTypePop(final List<MerchantTypeListBean.ListBean> data) {
        MerchantTypeAdapter merchantTypeAdapter = new MerchantTypeAdapter(_mActivity);
        merchantTypeAdapter.setmLists(data);
        merchant_type_btn.setBackgroundResource(R.drawable.arrow_up);
        View popView = _mActivity.getLayoutInflater().inflate(R.layout.layout_merchant_type_list, null);
        final PopupWindow popupWindow = new PopupWindow(popView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        ListView lv_merchType = (ListView) popView.findViewById(R.id.lv_type);
        lv_merchType.setAdapter(merchantTypeAdapter);
        lv_merchType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mMerchantTypeBean = data.get(position);
                mMerchantType = mMerchantTypeBean.getMerchClassName();
                merChantClassId = mMerchantTypeBean.getMerchClassId();
                rates_info_ll.setVisibility(View.VISIBLE);
                no_card_pays_merchant_type_tv.setText(mMerchantTypeBean.getMerchClassName());
                double fee = Double.valueOf(mMerchantTypeBean.getMerchClassFeeIncrement());
                rates_tv.setText(mMerchantTypeBean.getMerchClassFeeRate() + "%+" + CommonUtils.formatMoneyDouble(ArithUtil.div(fee, 100d)));
                double rates = Double.valueOf(mMerchantTypeBean.getMerchClassFeeRate());
                double service_charge = ArithUtil.mul(ArithUtil.div(rates, 100d), mAmount) + Double.valueOf(fee);
                service_charge = ArithUtil.getCeil(ArithUtil.div(service_charge, 100d), 2);
                service_charge_tv.setText(CommonUtils.formatMoneyDouble(service_charge) + "元");
                double arrival_amount = ArithUtil.div(mAmount, 100d) - service_charge;
                arrival_amount_tv.setText(CommonUtils.formatMoneyDouble(arrival_amount) + "元");
                popupWindow.dismiss();
            }
        });
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            ll_merchant_type.getLocationInWindow(a);
            popupWindow.showAtLocation(_mActivity.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + ll_merchant_type.getHeight() + CommonUtils.px2dp(20));
        } else {
            popupWindow.showAsDropDown(ll_merchant_type);
        }
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                merchant_type_btn.setBackgroundResource(R.drawable.arrow_down);
            }
        });
    }

    /**
     * 显示历史卡popwin
     *
     * @param v
     */
    private void showRecentCardNoListWindow(View v) {
        View popupView = _mActivity.getLayoutInflater().inflate(R.layout.layout_no_card_pay_list_card_no, null);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        }

        ListView listView = (ListView) popupView.findViewById(R.id.no_card_pay_card_no_lv);
        listView.setAdapter(mNoCardPayListCardNoAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NoCardPayListCardNoAdapter aNoCardPayListCardNoAdapter = (NoCardPayListCardNoAdapter) parent.getAdapter();
                if (aNoCardPayListCardNoAdapter.getCount() == 1) {
                    mPopupWindow.dismiss();
                    return;
                } else if (aNoCardPayListCardNoAdapter.getCount() - 1 == position) {
                    doDeleteHistoryBankCardList();
                } else {
                    mHistoryBankCardItem = aNoCardPayListCardNoAdapter.getItem(position);
                    no_card_pay_card_no.setTextWithOutFocus(CommonUtils.formattingCard(mHistoryBankCardItem.getCardNo()));
                    no_card_pay_card_no.setEnabled(false);
                    mPopupWindow.dismiss();
                }
            }
        });
        mNoCardPayListCardNoAdapter.notifyDataSetChanged();
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            v.getLocationInWindow(a);
            mPopupWindow.showAtLocation(_mActivity.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + v.getHeight() + CommonUtils.dp2px(20));
        } else {
            mPopupWindow.showAsDropDown(v);
        }
        mPopupWindow.update();
    }

    /**
     * 获取商户信息
     */
    private void getMerchinfo() {
        String newBankFlag = "1";
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(_mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, newBankFlag);
        mMinePresenterImpl.getMerchInfo(params, MerchInfo.class, true);
    }

    /**
     * 获取多费率
     */
    private void getMerchantTypeList() {
        mMerchantTypeList = new ArrayList<>();
        String newBankFlag = "1";
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(_mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, newBankFlag);
        params.put(BaseProtocolKey.TRADETYPE, NoCardPayConstant.TRADETYPE_UNIONPAYQUICK);
        //选择商户类型
        mMerchantTypeListPresenter.getMerchantTypeList(params, MerchantTypeListBean.class, true);
    }

    /**
     * 获取历史卡
     */
    private void getHistoryBankCard() {
        HashMap<String, Object> paramers = new HashMap<String, Object>();
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put(BaseProtocolKey.CLIENTCHANNEL, NoCardPayConfig.CLIENTCHANNEL);
        paramers.put(BaseProtocolKey.TRADETYPE, "1");
        mHistoryBankCardListPresenter.getHistoryBankCardList(paramers, HistoryBankCardListBean.class, true);
    }

    /**
     * 删除历史卡
     */
    private void doDeleteHistoryBankCardList() {
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.no_card_pay_delete), _mActivity.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("tradeType", "1");
                mHistoryBankCardListPresenter.doDelHistoryBankCardList(params, HistoryBankCardDelBean.class, true);
                no_card_pay_card_no.setText("");
                no_card_pay_card_no.setEnabled(true);
                dialog.dismiss();
                mPopupWindow.dismiss();
            }
        });
    }

    /**
     * 银联快捷支付
     */
    private void quickPay() {
        final HashMap<String, Object> paramers = new HashMap<>();
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        if (TextUtils.isEmpty(address)) {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.message_alert_no_found_gps), false, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    locationService.start();
                    dialog.dismiss();
                }
            });
            return;
        }
        HPLog.d(HPLog.SSX_TAG, "address:" + address);
        String cardNo = no_card_pay_card_no.getText().toString();
        cardNo = cardNo.replace(" ", "");
        if (no_card_pay_card_no.isEnabled()) {
            if (!CommonUtils.isLegalCard(cardNo)) {
                DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), getString(R.string.hint_input_right_card_no_tip), true);
                return;
            }
        }
        if (bIsShowMerchantType == true) {
            if (TextUtils.isEmpty(mMerchantType) || TextUtils.isEmpty(merChantClassId)) {
                DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), getString(R.string.selectMerchType), true);
                return;
            }
            quickPayReqBean.setMerchClassId(SecureManager.getInstance().des(merChantClassId, 1, null));
        }
        String merchantCode = AccountUtils.getMerchantCode(_mActivity);

        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String location = latitude.toString() + "," + longtitude.toString();
        String clientVersion = "v" + ClientEngine.getInstance().VERSION;
        HPLog.d(HPLog.SSX_TAG, "location:" + location);

        if (no_card_pay_card_no.isEnabled()) {
            quickPayReqBean.setCardNo(SecureManager.getInstance().des(cardNo, 1, null));
            paramers.put(BaseProtocolKey.CARDNO1, quickPayReqBean.getCardNo());
            quickPayReqBean.setHistroyBankNo(false);
            quickPayReqBean.setCardID(null);
            quickPayReqBean.setHistoryCardNo("");
            paramers.remove(BaseProtocolKey.CARDID);
        } else {
            if (mHistoryBankCardItem == null || TextUtils.isEmpty(mHistoryBankCardItem.getCardID())) {
                DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), getString(R.string.hint_input_right_card_no_tip), true);
                return;
            }
            String cardId = mHistoryBankCardItem.getCardID();
            quickPayReqBean.setCardID(SecureManager.getInstance().des(cardId, 1, null));
            paramers.put(BaseProtocolKey.CARDID, quickPayReqBean.getCardID());
            quickPayReqBean.setCardNo(null);
            quickPayReqBean.setHistroyBankNo(true);
            quickPayReqBean.setHistoryCardNo(mHistoryBankCardItem.getCardNo());
            paramers.remove(BaseProtocolKey.CARDNO1);
        }
        quickPayReqBean.setMerchantCode(SecureManager.getInstance().des(merchantCode, 1, null));
        quickPayReqBean.setOperateType(NoCardPayConstant.PAY);
        quickPayReqBean.setAmount(SecureManager.getInstance().des(String.valueOf(Double.valueOf(mAmount).intValue()), 1, null));
        quickPayReqBean.setChannel(SecureManager.getInstance().des(NoCardPayConfig.CHANNEL, 1, null));
        quickPayReqBean.setClientChannel(SecureManager.getInstance().des(NoCardPayConfig.CLIENTCHANNEL, 1, null));
        quickPayReqBean.setAddress(SecureManager.getInstance().des(address, 1, null));
        quickPayReqBean.setLocation(SecureManager.getInstance().des(location, 1, null));
        quickPayReqBean.setClientVersion(SecureManager.getInstance().des(clientVersion, 1, null));

        paramers.put(BaseProtocolKey.OPERATETYPE, quickPayReqBean.getOperateType());
        paramers.put(BaseProtocolKey.MERCHANTCODE, quickPayReqBean.getMerchantCode());
        paramers.put(BaseProtocolKey.MERCHCLASSID, quickPayReqBean.getMerchClassId());
        paramers.put(BaseProtocolKey.AMOUNT, quickPayReqBean.getAmount());
        paramers.put(BaseProtocolKey.CHANNEL, quickPayReqBean.getChannel());
        paramers.put(BaseProtocolKey.KEY_ADDRESS, quickPayReqBean.getAddress());
        paramers.put(BaseProtocolKey.KEY_LOCATION, quickPayReqBean.getLocation());
        paramers.put(BaseProtocolKey.CLIENTCHANNEL, quickPayReqBean.getClientChannel());
        paramers.put(BaseProtocolKey.CLIENTVERSION, quickPayReqBean.getClientVersion());


        String content = String.format(_mActivity.getString(R.string.hint_sure_pay), CommonUtils.formatMoneyDouble(ArithUtil.div(mAmount, 100d)));
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.pay_tip), content, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                unionPayQuickPresenter.quickUnioPay(paramers, true);
            }
        }, _mActivity.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

    }

    @Override
    public void queryHistorySuccess(HistoryBankCardListBean response) {
        mNoCardPayListCardNoAdapter.setData(response.getList());
        mNoCardPayListCardNoAdapter.notifyDataSetChanged();
        showRecentCardNoListWindow(ll_card);
    }

    @Override
    public void querySuccess(MerchInfo merchInfo) {
        this.mMerchInfo = merchInfo;
        String name = mMerchInfo.getName();
        name = SecureManager.getInstance().des(name, 0, null);
        no_card_pay_user_name_tv.setText(name);
    }

    @Override
    public void getPaymentResult(final UnionQuickPayRespBean quickPayBean) {
        /**
         * N
         * 0 表示失败
         * 1 表示成功，
         * 2 卡片未开通快捷/开通失败
         */
        if (quickPayBean.getStatus() == 0) {
            startWithPop(TransactionResultsFailFragment.newInstance(quickPayBean));
        } else if (quickPayBean.getStatus() == 1) {
            startWithPop(TransactionResultsSuccessFragment.newInstance(quickPayBean));
        } else if (quickPayBean.getStatus() == 2) {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.tip), _mActivity.getString(R.string.new_no_quick), false);
//银联快捷功能暂时屏蔽
/*            DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), getString(R.string.not_open_unionpay), _mActivity.getResources().getString(R.string.dialog_cancle), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }, _mActivity.getResources().getString(R.string.dialog_open), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startWithPop(OpenUnioQuickPayFragment.newInstance(quickPayReqBean, quickPayBean));
                    dialog.dismiss();
                }
            });*/

        }

    }

    @Override
    public void queryMerchantTypeSuccess(MerchantTypeListBean merchantTypeListBean) {
        if (merchantTypeListBean.getList() == null || merchantTypeListBean.getList().size() == 0) {
            ll_merchant_type.setVisibility(View.GONE);
            bIsShowMerchantType = false;

        } else {
            ll_merchant_type.setVisibility(View.VISIBLE);
            bIsShowMerchantType = true;
            for (MerchantTypeListBean.ListBean enMerchantType : merchantTypeListBean.getList()) {
                MerchantTypeListBean.ListBean desMerchantType = new MerchantTypeListBean.ListBean();
                String typeCode = SecureManager.getInstance().des(enMerchantType.getMerchClassId(), 0, null);
                String typeName = SecureManager.getInstance().des(enMerchantType.getMerchClassName(), 0, null);
                String merchantTypeFee = SecureManager.getInstance().des(enMerchantType.getMerchClassFeeRate(), 0, null);
                String merchantTypeFeeIncrement = SecureManager.getInstance().des(enMerchantType.getMerchClassFeeIncrement(), 0, null);
                HPLog.i(HPLog.SSX_TAG, "queryMerchantTypeSuccess typeCode:" + typeCode);
                HPLog.i(HPLog.SSX_TAG, "queryMerchantTypeSuccess typeName:" + typeName);
                desMerchantType.setMerchClassId(typeCode);
                desMerchantType.setMerchClassName(typeName);
                desMerchantType.setMerchClassFeeRate(merchantTypeFee);
                desMerchantType.setMerchClassFeeIncrement(merchantTypeFeeIncrement);
                mMerchantTypeList.add(desMerchantType);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == isCardRequestCode) {
            no_card_pay_card_no.setEnabled(true);
            if (resultCode == RESULT_OK && data != null) {
                long time = data.getLongExtra(ISCardScanActivity.EXTRA_KEY_TIME, 0);
                CCREngine.ResultData result = (CCREngine.ResultData) data.getSerializableExtra(ISCardScanActivity.EXTRA_KEY_RESULT);
                // 卡号
                String cardNumber = result.getCardNumber();
                no_card_pay_card_no.setTextWithOutFocus(cardNumber);
            } else {
                no_card_pay_card_no.setTextWithOutFocus("");
                HPLog.e("isCCCard", "返回失败,未拍照");
            }
        } else if (requestCode == REQUEST_CODE_SETTING) {
            if (AndPermission.hasPermission(_mActivity, Permission.LOCATION)) {
                quickPay();
            }
        }
    }

    @Override
    public void onDestroy() {
        locationService.unregisterListener();
        locationService.stop();
        super.onDestroy();
    }
}
